from django.shortcuts import render
from django.http import HttpResponse

from .TypesViews import GetTypesAll
from .IndexViews import uploads
from ..models import Goods,Types
from django.core.urlresolvers import reverse

from django.contrib.auth.decorators import permission_required
from ..models import Goods,Types
from . IndexViews import uploads
from lzy.settings import BASE_DIR
# 导入分类的数据的函数
from .TypesViews import GetTypesAll
import os



# 添加
@permission_required('myadmin.insert_goods',raise_exception = True)
def goodsadd(request):
    
    context ={'typelist':GetTypesAll()}
    
    return  render(request,'admin/goods/add.html',context) 

# 执行数据的添加
@permission_required('myadmin.insert_goods',raise_exception = True)
def goodsinsert(request):
    try:
        # 接受数据
        data = request.POST.dict()
        # 删除数据csrf
        data.pop('csrfmiddlewaretoken')
        # 上传图片
        myfile = request.FILES.get('pic',None)
        # 判断是否有文件上传
        if not myfile:
            return HttpResponse('<script>alert("必须有图片上传");location.href="'+reverse('myadmin_goods_add)')+'"</script>')

        # 执行文件上传
        data['pic'] = uploads(myfile)
        #处理选择的分类数据
        data['tid'] = Types.objects.get(id=data['tid'])
        print(data)
        # 数据的添加
        Goods.objects.create(**data)

        return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_goods_add')+'"</script>')


# 列表
@permission_required('myadmin.show_goods',raise_exception = True)
def goodsindex(request):
    
    # 获取所有的商品数据
    goodslist = Goods.objects.exclude(status=3)
    # 分配数据
    # context = {'goodslist':goodslist}

    # goods =  GetTypesAll()
    # 接受参数
    keys = request.GET.get('types',None)
    keywords = request.GET.get('keywords',None)
    print(keys,keywords)
    # 判断是否有搜索条件
    if keys:  
        if keys == 'all':
        # 多字段的查询
            from django.db.models import Q
            goodslist = goodslist.filter(Q(title__contains=keywords)|Q(price__contains=keywords))
        else:
            data ={keys+'__contains':keywords}
            print(data)
            goodslist = goodslist.filter(**data)

 # 数据分页
    from django.core.paginator import Paginator
    # 实例化分页对象
    p = Paginator(goodslist,10)
    # 获取当前的页码数
    page = request.GET.get('page',1)
    # 获取当前页的数据
    goodslist = p.page(page)
    # 获取所有的页码列表
    # pages = p.page_range

    # 分配数据
    context = {'goodslist':goodslist}

    # 加载模板
    return render(request,'admin/goods/index.html',context)


# 删除
@permission_required('myadmin.del_goods',raise_exception = True)
def goodsdelete(request,uid):
    try:
        # 获取删除的数据
        ob = Goods.objects.get(id=uid)
        # 修改状态
        ob.status=3
        ob.save()
        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        # 操作失败
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_goods_index')+'"</script>')


# 修改
@permission_required('myadmin.insert_goods',raise_exception = True)
def goodsedit(request,uid):
    # context ={'typelist':GetTypesAll()}
        # 获取修改的数据
    # uid  = request.GET.get('uid')
    ob = Goods.objects.get(id=uid)
    # print(ob)
      # 分配数据 
    context={'uinfo':ob,'typeslist':GetTypesAll()}
    # print(context)
      # 返回页面
    return render(request,'admin/goods/edit.html',context)


 # 执行修改
@permission_required('myadmin.edit_goods',raise_exception = True)
def goodsupdate(request):
    try:
        # 接受数据
        data = request.POST.dict()
        # 删除数据csrf
        data.pop('csrfmiddlewaretoken')
        print(data)
        # 获取对象
        ob = Goods.objects.get(id=data['id'])
        # print('ob')
        # 更新数据
        ob.tid = Types.objects.get(id=data['tid'])
        print(data)
        #  # 判断是否有图片上传
        myfile = request.FILES.get('pic',None)  
        # # 有上传,删除原有图片数据
        if myfile:
        # # 删除原来的图片
            os.remove(BASE_DIR+ob.pic)
        #     # 执行文件上传,并更新头像数据
            ob.pic = uploads(myfile)
        ob.title = data['title']
        ob.price = data['price']
        ob.num = data['num']
        ob.status = data['status']
        ob.info = data['info']
        # 执行更新    
        ob.save()

        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        # 操作失败
        return HttpResponse('<script>alert("修改失败");location.href="'+reverse('myadmin_goods_edit')+'"</script>')
